import axios from 'axios'
import { Message } from 'element-ui'
import QS from 'qs'

const baseUrl = process.env.VUE_APP_BASE_API || ''

const service = axios.create({
  // baseURL: baseUrl // api 的 base_url
  // withCredentials: false
})

// 请求拦截器
service.interceptors.request.use(config => {
  if (config.headers['Content-Type'] !== 'application/json;charset=UTF-8') {
    // 数据序列化
    config.data = QS.stringify(config.data)
  }
  return config
}, error => {
  Message.error(`请求拦截器${error}`)
  return Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(res => {
  if (res && res.data) {
    return Promise.resolve(res.data)
  }
  // Message.error(res.data)

  return res
}, err => {
  // 响应结束
  // loadingInstance.close()
  if (err && err.response) {
    switch (err.response.status) {
      case 400:
        err.message = '错误请求'
        break
      case 401:
        err.message = 'session过期，请从新登陆'
        Message.error(err.message)
        window.location.hash = '/'
        break
      case 403:
        err.message = '拒绝访问'
        break
      case 404:
        err.message = '请求错误,未找到该资源'
        break
      case 405:
        err.message = '请求方法未允许'
        break
      case 408:
        err.message = '请求超时'
        break
      case 500:
        err.message = '服务器端出错'
        break
      case 501:
        err.message = '网络未实现'
        break
      case 502:
        err.message = '网络错误'
        break
      case 503:
        err.message = '服务不可用'
        break
      case 504:
        err.message = '网络超时'
        break
      case 505:
        err.message = 'http版本不支持该请求'
        break
      default:
        err.message = `连接错误${err.response.status}`
    }
  } else {
    err.message = '连接到服务器失败'
  }
  Message.closeAll()
  Message.error(err.message)
})

const baseMethod = (url, params, method) => new Promise((resolve, reject) => {
  service({
    method,
    url,
    params
  }).then(res => {
    resolve(res)
  }).catch(error => {
    reject(error)
  })
})

export const post = (url, data, headers = true) => new Promise((resolve, reject) => {
  service({
    method: 'post',
    url,
    data,
    headers: {
      'Content-Type': headers ? 'application/x-www-form-urlencoded;charset=UTF-8' : 'application/json;charset=UTF-8'
    }
  }).then(res => {
    resolve(res)
  }).catch(err => {
    reject(err)
  })
})

export const get = (url, params) => baseMethod(url, params, 'get')

export const deletes = (url, params) => baseMethod(url, params, 'delete')

export const downFile = fileId => {
  get('/sys/file/checkFileExist', { fileId }).then(res => {
    if (res.state) {
      const { path, fileName } = res.obj
      const values = [
        {
          key: 'path',
          value: path
        },
        {
          key: 'fileName',
          value: fileName
        }
      ]
      // 模拟提交请求
      mockPost('sys/file/downFile', values)
    } else {
      Message.error(res.obj)
    }
  })
}

// 模拟表单提交（附件下载）
export const mockPost = (api, maps = []) => {
  if (maps.length === 0) {
    throw new Error('maps length of 0')
  }
  const url = `${baseUrl}${api}`
  const form = document.createElement('form')
  const body = document.querySelector('body')
  form.setAttribute('action', url)
  form.setAttribute('method', 'post')
  // 数据拼接
  maps.forEach(item => {
    const { key, value } = item
    const input = document.createElement('input')
    input.setAttribute('name', key)
    input.setAttribute('value', value)
    form.append(input)
  })
  body.append(form)
  form.submit()
  form.remove()
}
